package EDesign23;

public class BTravelStrategy {


    // 1 **************************  工厂模式  ****************************
    public interface TravelStrategy {
        int calculateMinCost();
    }


    public class SelfDrivingStrategy implements TravelStrategy {

        @Override
        public int calculateMinCost() {
            return 30;
        }
    }

    public class BicycleStrategy implements TravelStrategy {

        @Override
        public int calculateMinCost() {
            return 20;
        }
    }

    public class PublicTransportStrategy implements TravelStrategy {

        @Override
        public int calculateMinCost() {
            return 10;
        }
    }

    public class TravelStrategyFactory {
        public TravelStrategy createTravelStrategy(String travelWay) {
            if ("selfDriving".equals(travelWay)) {
                return new SelfDrivingStrategy();
            }
            if ("bicycle".equals(travelWay)) {
                return new BicycleStrategy();
            } else {
                return new PublicTransportStrategy();
            }
        }
    }

    public class TravelService {
        private TravelStrategyFactory travelStrategyFactory = new TravelStrategyFactory();

        public int calculateMinCost(String travelWay) {
            TravelStrategy travelStrategy = travelStrategyFactory.createTravelStrategy(travelWay);
            return travelStrategy.calculateMinCost();
        }
    }


    // 1 **************************  策略模式  ****************************

    public class StrategyContext {
        private TravelStrategy strategy;

        public StrategyContext(TravelStrategy strategy) {
            this.strategy = strategy;
        }

        public int calculateMinCost() {
            return strategy.calculateMinCost();
        }

    }

    public class TravelService2 {
        private StrategyContext strategyContext;

        public int calculateMinCost(String travelWay) {

            if ("selfDriving".equals(travelWay)) {
                strategyContext = new StrategyContext(new SelfDrivingStrategy());
            }
            if ("bicycle".equals(travelWay)) {
                strategyContext = new StrategyContext(new BicycleStrategy());
            } else {
                strategyContext = new StrategyContext(new PublicTransportStrategy());
            }

            return strategyContext.calculateMinCost();
        }
    }
}
